<template>
	<globalModal
		:title="title"
		:visible="visible"
		:confirmLoading="confirmLoading"
		@ok="handleOk"
		@cancel="handleCancel"
	>
		<a-spin :spinning="confirmLoading">
			<a-form :form="form" autocomplete="off" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<a-form-item label="所属机构" v-if="isAdmin">
					<a-select
						allowClear
						:disabled="!isAdd"
						@change="changeOrg"
						v-decorator="['orgId', { rules: [{ required: isAdmin, message: '所属机构' }] }]"
						placeholder="所属机构"
					>
						<a-select-option :value="item.orgId" v-for="(item, index) in orgList" :key="index">{{
							item.orgName
						}}</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="上级部门">
					<a-tree-select
						:disabled="!isAdd"
						placeholder="请选择上级部门"
						:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
						:tree-data="deptTree"
						show-search
						:replaceFields="replaceFields"
						@change="changeDept"
						treeNodeFilterProp="title"
						v-decorator="['parentId']"
					/>
				</a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="部门名称">
					<a-input
						placeholder="部门名称"
						v-decorator="[
							'deptName',
							{
								rules: [
									{ required: true, message: '请输入部门名称' },
									{ max: 30, message: '部门名称不超过30个字符' },
								],
							},
						]"
					/>
				</a-form-item>

				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序号" extra="数据越小越靠前">
					<a-input-number
						placeholder="排序号"
						v-decorator="['orderNum', { initialValue: 1 }]"
						:min="1"
						:precision="0"
						class="w100"
					/>
				</a-form-item>
				<a-form-item label="部门地址">
					<a-cascader
						v-decorator="[
							'geo',
							{
								rules: [{ required: true, message: '请选择部门地址' }],
							},
						]"
						@change="changeAddr"
						:options="areaData"
						:load-data="loadData"
						change-on-select
						:field-names="{ label: 'xzqhmc', value: 'xzqhbm', children: 'children' }"
						style="width: 100%"
						placeholder="部门地址"
						:show-search="{ filter }"
					>
						<template slot="displayRender" slot-scope="{ labels, selectedOptions }">
							<span v-for="(label, index) in labels" :key="selectedOptions[index].value">{{
								label
							}}</span>
						</template>
					</a-cascader>
				</a-form-item>
			</a-form>
		</a-spin>
	</globalModal>
</template>

<script>
import { sysManageapi } from '@/api/index.js'
import { ModalMixins } from '@/mixins'
import { mapState, mapActions } from 'vuex'
let cache = {}
function getOrgbyDept(tree, value) {
	for (var i = 0; i < tree.length; i++) {
		let item = tree[i]
		if (JSON.stringify(item).indexOf('"deptId":' + value) > -1) {
			if (item.deptId == value) {
				return item
			} else {
				return getOrgbyDept(item.children, value)
			}
			break
		}
	}
}
export default {
	name: 'addOrEditDeptModal',
	mixins: [ModalMixins],
	data() {
		return {
			orgName: '',
			orgId: '',
			orgList: [],
			parentId: '',
			replaceFields: { children: 'children', title: 'deptName', key: 'deptId', value: 'deptId' },
			allDeptTree: [],
			areaData: [],
		}
	},
	computed: {
		deptTree() {
			return [
				{
					deptId: 0,
					value: 0,
					deptName: '主部门',
					children: [...this.allDeptTree],
				},
			]
		},
	},
	created() {},

	methods: {
		async getDefaultList() {
			let { province, city, area } = this.mdl
			if (province && city && area) {
				this.mdl.geo = [province, city, area]
			}

			this.parentId = this.mdl.parentId || undefined
			if (this.isAdmin && this.orgList.length == 0) {
				this.getAllOrgList()
			}
			this.orgId = this.mdl.orgId || null
			this.getDeptTree()
			let areaData = await this.getCitysInfo('')
			if (province) {
				let provinceIndex = areaData.findIndex((item) => item.xzqhbm == province)
				if (provinceIndex > -1) {
					areaData[provinceIndex].children = await this.getCitysInfo(province)
					if (city) {
						let index = areaData[provinceIndex].children.findIndex((item) => item.xzqhbm == city)
						if (index > -1) {
							areaData[provinceIndex].children[index].children = await this.getCitysInfo(city)
						}
					}
				}
			}
			this.areaData = [...areaData]
		},
		getAllOrgList() {
			this.$postAction(sysManageapi.orgUrl.getAllList).then((res) => {
				if (res && res.code == 1) {
					this.orgList = res.data
				}
			})
		},
		setAddFieldsValue() {
			this.form.setFieldsValue({ parentId: this.mdl.parentId || undefined, orgId: this.mdl.orgId || undefined })
		},

		changeOrg(value, e, extra) {
			this.orgId = value
			this.getDeptTree()
			this.form.setFieldsValue({ parentId: undefined })
		},
		changeDept(value, e, extra) {
			/* 编辑是，需要判断上级部门不能是当前部门 */
			if (!this.isAdd && value == this.mdl.deptId) {
				this.$message.error('上级校区不能选择自身校区')
				this.$nextTick(() => {
					this.form.setFieldsValue({ parentId: this.parentId })
				})
				return false
			}
			this.parentId = value
		},
		getDeptTree() {
			this.$postAction(sysManageapi.deptUrl.getList, {
				orgId: this.orgId,
			}).then((res) => {
				if (res && res.code == 1) {
					this.allDeptTree = [...res.data]
				}
			})
		},
		getCitysInfo(id) {
			return new Promise((resolve, reject) => {
				let key = 'address_' + id
				if (cache[key] && cache[key].length > 0) {
					resolve(cache[key])
				} else {
					this.getCitys(id)
						.then((res) => {
							console.log('res', res)
							let list = res.data.map((item) => {
								return {
									...item,
									isLeaf: item.level == 3,
								}
							})
							cache[key] = list
							resolve(list)
						})
						.catch((err) => {
							reject(err)
						})
				}
			})
		},
		async loadData(selectedOptions) {
			const targetOption = selectedOptions[selectedOptions.length - 1]
			console.log('e', 'haha', targetOption)
			targetOption.loading = true
			let addressList = await this.getCitysInfo(targetOption.xzqhbm)
			targetOption.loading = false
			targetOption.children = addressList
			this.areaData = [...this.areaData]
		},
		getCitys(cid) {
			return this.$postAction(sysManageapi.deptUrl.getRegion + '?pXzqhbm=' + cid)
		},
		changeAddr(e, selectedOptions) {
			// let xzqhbm = '';
			// if (selectedOptions && selectedOptions.length > 0) {
			// 	xzqhbm = selectedOptions[selectedOptions.length - 1].code;
			// }
			// console.log('e', e, selectedOptions, xzqhbm);
			// this.form.setFieldsValue({
			// 	xzqhbm
			// });
		},
		/**
		 * 点击确认按钮
		 */
		handleOk() {
			// 触发表单验证
			this.form.validateFields((err, values) => {
				// 验证表单没错误
				console.log('values', values)
				if (!err) {
					/* 处理地址 */
					let id = this.mdl[this.editKey]
					let geo = values['geo']

					let parameter = Object.assign(
						{},
						values,
						id
							? {
									[this.editKey]: id,
							  }
							: ''
					)
					parameter.province = geo && geo.length > 2 ? geo[0] : null
					parameter.city = geo && geo.length > 2 ? geo[1] : null
					parameter.area = geo && geo.length > 2 ? geo[2] : null
					this.saveInfo(this.isAdd ? this.api.add : this.api.edit, parameter)
				}
			})
		},
		filter(inputValue, path) {
			return path.some((option) => option.xzqhmc.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
		},
	},
}
</script>

<style scoped></style>
